<?php
//$opt= getopt('messagelog_id:message_type:');
$longopt = array(
    'messagelog_id:',
    'env:'
);
$params =  getopt('', $longopt);
$hostname = '114.215.138.1';//服务端接收的ip
$port = 1883;//服务端接收的端口
$udp_connect = 0;
function encode($buffer)
{
    $total_length = 4 + strlen($buffer);
    return pack('N', $total_length) . $buffer;
}

function decode($buffer)
{
    return substr($buffer, 4);
}

function json_pack($controller_name, $method_name, $data){
    $pdata['controller_name'] = $controller_name;
    $pdata['method_name'] = $method_name;
    $pdata['data'] = $data;
    return json_encode($pdata, JSON_UNESCAPED_SLASHES);
}
$client = new \swoole_client(SWOOLE_SOCK_TCP,SWOOLE_SOCK_ASYNC);
$client->params = $params;
$client->set(array(
    //'open_length_check' => 1, 关闭后可以receive成功 https://wiki.swoole.com/wiki/page/287.html
    'package_length_type' => 'N',
    'package_length_offset' => 0,       //第N个字节是包长度的值
    'package_body_offset' => 0,       //第几个字节开始计算长度
    'package_max_length' => 2000000,  //协议最大长度
));

$client->on("connect", 'connect');

$client->on("receive", 'receive');

$client->on("error", function ($cli) {
    exit("error\n");
});

$client->on("close", function ($cli) {
    print_r("close\n");
});

$client->connect($hostname, $port, 0.5,$udp_connect);

function connect($cli)
{
    print_r("connect callback\n");
    var_dump($cli);
    $result = $cli->send(encode(json_pack('TestController', 'testTcp', $cli->params)));
    if(!$result){
        print_r($cli->errCode);
    }
}

function receive($cli, $data)
{
    print_r("receive backaaaa\n");print_r("receive rere\n");
    print_r($data);
    $data = decode($data);
    print_r("\n");
    $data_arr = json_decode($data);
    print_r("hehehe\n");
    print_r($data_arr);
}